import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart';

main() {
  runApp(MaterialApp(home: Page0()));
}

class Page0 extends StatefulWidget {
  const Page0({super.key});

  @override
  State<StatefulWidget> createState() => _Page0State();
}

class _Page0State extends State<Page0> {
  Future<sql.Database> getDb() async {
    // 获取可存放路径
    String p = await sql.getDatabasesPath();
    print('sqflite 保存数据所在目录为 ${p}');
    // join() 来自 path/path.dart，拼接路径
    return await sql.openDatabase(join(p, 'mydb.db'));
  }

  String tableName = 'record2';

  void createTable() async {
    var db = await getDb();
    db.execute("""create table if not exists ${tableName}(
      id integer primary key autoincrement,
      money text, date1 text)
      """);
  }

  void insertOne() async {
    var db = await getDb();
    var res =
        await db.insert(tableName, {'money': '200', 'date1': '2023.11.6'});
    print('插入状态为 ${res}');
  }

  void selectAll() async {
    var db = await getDb();
    var allData = await db.query('${tableName}', orderBy: 'id');
    print('查询到的数据为:');
    allData.forEach((e) {
      print(e);
    });
    print('------');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 应用栏
      appBar: AppBar(
        title: const Text('SQFLITE'), // 标题
      ),
      body: Column(
        children: [
          ElevatedButton(onPressed: createTable, child: Text('创建表格')),
          ElevatedButton(onPressed: selectAll, child: Text('查询所有数据')),
          ElevatedButton(onPressed: insertOne, child: Text('添加数据')),
        ],
      ),
    );
  }
}
